package com.cg.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.cg.config.MyAlipayConfig;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class AliPayUtil {


    @Resource
    private MyAlipayConfig myAlipayConfig;

    public String toPay(String orderNo,String totalAmount) throws AlipayApiException {
        //封装请求参数
        String privateKey = myAlipayConfig.getPrivateKey();
        String alipayPublicKey = myAlipayConfig.getAlipayPublicKey();
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl(myAlipayConfig.getServerUrl());
        alipayConfig.setAppId(myAlipayConfig.getAppId());
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat(myAlipayConfig.getFormat());
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset(myAlipayConfig.getCharset());
        alipayConfig.setSignType(myAlipayConfig.getSignType());
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(orderNo);
        model.setTotalAmount(totalAmount);
        model.setSubject(myAlipayConfig.getSubject());
        model.setProductCode(myAlipayConfig.getProductCode());
        request.setBizModel(model);

        //同步通知地址
        request.setReturnUrl(myAlipayConfig.getReturnUrl());
        //异步通知地址
        request.setNotifyUrl(myAlipayConfig.getNotifyUrl());

        //发起请求
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        //处理返回
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return response.getBody();
    }

}
